<template>
  <div style="height: 100vh; display: flex; flex-direction: column; background: #f5f5f5;">
    <!-- 顶部导航栏 - 固定高度 -->
    <div style="height: 80px; background: white; border-bottom: 1px solid #ddd; display: flex; align-items: center; padding: 0 30px; flex-shrink: 0;">
      <a-button type="link" @click="goBack" style="padding: 0; margin-right: 20px; font-size: 16px;">
        <LeftOutlined />
        返回
      </a-button>
      <h1 style="color: #1890ff; margin: 0; font-size: 24px;">文档详情</h1>
    </div>
    
    <!-- 主体内容 -->
    <div style="flex: 1; padding: 40px 20px; background: #f5f5f5; width: 100%; box-sizing: border-box;">
      <a-spin :spinning="loading" style="width: 100%; display: block;">
        
        <!-- 文档详情卡片 -->
        <div v-if="documentData.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px; width: 100%;">
          <!-- 文档基本信息 -->
          <div style="border-bottom: 1px solid #f0f0f0; padding-bottom: 30px; margin-bottom: 30px;">
            <h2 style="font-size: 28px; color: #333; margin-bottom: 20px;">{{ documentData.title }}</h2>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-bottom: 20px;">
              <div>
                <span style="font-weight: 600; color: #666;">文档类型：</span>
                <a-tag :color="getDocTypeColor(documentData.docType)">{{ getDocTypeText(documentData.docType) }}</a-tag>
              </div>
              
              <div>
                <span style="font-weight: 600; color: #666;">发布日期：</span>
                <span style="font-size: 16px;">{{ documentData.publishDate }}</span>
              </div>
              
              <div>
                <span style="font-weight: 600; color: #666;">来源：</span>
                <span style="font-size: 16px;">{{ documentData.source }}</span>
              </div>
            </div>
            
            <!-- 标签 -->
            <div v-if="documentData.tags && documentData.tags.length > 0" style="margin-bottom: 20px;">
              <span style="font-weight: 600; color: #666; margin-right: 12px;">标签：</span>
              <a-tag 
                v-for="tag in documentData.tags" 
                :key="tag.id" 
                :color="tag.color"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ tag.name }}
                <span style="font-size: 12px; opacity: 0.8;">({{ tag.usageCount }})</span>
              </a-tag>
            </div>
            
            <!-- 关键词 -->
            <div v-if="documentData.keywords">
              <span style="font-weight: 600; color: #666;">关键词：</span>
              <span style="color: #999;">{{ documentData.keywords }}</span>
            </div>
          </div>
          
          <!-- 文档内容 -->
          <div>
            <h3 style="font-size: 20px; color: #333; margin-bottom: 20px;">文档内容</h3>
            <div style="background: #fafafa; padding: 30px; border-radius: 8px; line-height: 1.8; font-size: 16px; white-space: pre-wrap;">{{ documentData.content }}</div>
          </div>
        </div>
        
        <!-- 操作按钮区域 -->
        <div v-if="documentData.id" style="background: white; padding: 20px 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px; display: flex; justify-content: flex-end; gap: 12px;">
          <a-button 
            v-if="documentData.fileUrl"
            type="default"
            @click="handlePreview"
            :loading="previewLoading"
          >
            <EyeOutlined />
            预览文件
          </a-button>
          <a-button 
            v-if="documentData.fileUrl"
            type="default"
            @click="handleDownload"
          >
            <DownloadOutlined />
            下载文件
          </a-button>
          <a-button 
            :type="isFavorited ? 'primary' : 'default'" 
            :icon="isFavorited ? 'HeartFilled' : 'HeartOutlined'"
            @click="handleToggleFavorite"
            :loading="favoriteLoading"
          >
            {{ isFavorited ? '已收藏' : '收藏' }}
          </a-button>
        </div>
        
        <!-- 相关案件 -->
        <div v-if="documentData.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="font-size: 18px; color: #333; margin: 0; display: flex; align-items: center;">
              <span style="margin-right: 8px;">⚖️</span>
              相关案件
            </h3>
          </div>
          
          <a-spin :spinning="casesLoading">
            <div v-if="relatedCases.length > 0">
              <a-row :gutter="[20, 20]">
                <a-col :span="8" v-for="item in relatedCases" :key="item.id">
                  <a-card hoverable style="height: 180px; cursor: pointer;" @click="viewCaseDetail(item)">
                    <div style="height: 100%; display: flex; flex-direction: column; justify-content: space-between;">
                      <div>
                        <h4 style="margin: 0 0 8px 0; color: #1890ff; font-size: 16px; font-weight: 600;">{{ item.caseNumber }}</h4>
                        <p style="margin: 0 0 8px 0; color: #666; font-size: 14px;">{{ item.parties }}</p>
                      </div>
                      <div style="display: flex; justify-content: space-between; align-items: center;">
                        <a-tag :color="getCaseStatusColor(item.status)">{{ getCaseStatusText(item.status) }}</a-tag>
                        <span style="font-size: 12px; color: #999;">{{ item.createTime }}</span>
                      </div>
                    </div>
                  </a-card>
                </a-col>
              </a-row>
              
              <div v-if="casesPagination.total > casesPagination.pageSize" style="text-align: center; margin-top: 20px;">
                <a-pagination
                  v-model:current="casesPagination.current"
                  v-model:page-size="casesPagination.pageSize"
                  :total="casesPagination.total"
                  :show-size-changer="false"
                  :show-quick-jumper="true"
                  @change="loadRelatedCases"
                />
              </div>
            </div>
            
            <div v-else style="text-align: center; padding: 40px; color: #999;">
              <div style="font-size: 36px; margin-bottom: 12px;">📋</div>
              <p>暂无相关案件</p>
            </div>
          </a-spin>
        </div>
        
        <!-- 相关法律条款 -->
        <div v-if="documentData.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="font-size: 18px; color: #333; margin: 0; display: flex; align-items: center;">
              <span style="margin-right: 8px;">📖</span>
              相关法律条款
            </h3>
          </div>
          
          <a-spin :spinning="lawsLoading">
            <div v-if="relatedLaws.length > 0">
              <a-row :gutter="[20, 20]">
                <a-col :span="8" v-for="item in relatedLaws" :key="item.id">
                  <a-card hoverable style="height: 180px; cursor: pointer;" @click="viewLawDetail(item)">
                    <div style="height: 100%; display: flex; flex-direction: column; justify-content: space-between;">
                      <div>
                        <h4 style="margin: 0 0 8px 0; color: #1890ff; font-size: 16px; font-weight: 600;">{{ item.lawCode }}</h4>
                        <p style="margin: 0 0 8px 0; color: #666; font-size: 14px; line-height: 1.4;">
                          {{ item.content.length > 80 ? item.content.substring(0, 80) + '...' : item.content }}
                        </p>
                      </div>
                      <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span style="font-size: 12px; color: #999;">{{ item.documentTitle }}</span>
                        <span style="font-size: 12px; color: #999;">{{ item.effectiveDate }}</span>
                      </div>
                    </div>
                  </a-card>
                </a-col>
              </a-row>
              
              <div v-if="lawsPagination.total > lawsPagination.pageSize" style="text-align: center; margin-top: 20px;">
                <a-pagination
                  v-model:current="lawsPagination.current"
                  v-model:page-size="lawsPagination.pageSize"
                  :total="lawsPagination.total"
                  :show-size-changer="false"
                  :show-quick-jumper="true"
                  @change="loadRelatedLaws"
                />
              </div>
            </div>
            
            <div v-else style="text-align: center; padding: 40px; color: #999;">
              <div style="font-size: 36px; margin-bottom: 12px;">📜</div>
              <p>暂无相关法律条款</p>
            </div>
          </a-spin>
        </div>
        
        <!-- 评论区域 -->
        <div v-if="documentData.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="font-size: 18px; color: #333; margin: 0; display: flex; align-items: center;">
              <span style="margin-right: 8px;">💬</span>
              评论 ({{ commentsPagination.total }})
            </h3>
          </div>
          
          <!-- 发表评论 -->
          <div style="margin-bottom: 30px; padding: 20px; background: #fafafa; border-radius: 8px;">
            <a-textarea
              v-model:value="newComment"
              placeholder="请输入您的评论..."
              :rows="4"
              :max-length="500"
              show-count
              style="margin-bottom: 12px;"
            />
            <a-button type="primary" @click="handleAddComment" :loading="commentLoading">
              发表评论
            </a-button>
          </div>
          
          <!-- 评论列表 -->
          <a-spin :spinning="commentsLoading">
            <div v-if="comments.length > 0" style="display: flex; flex-direction: column; gap: 16px;">
              <div v-for="comment in comments" :key="comment.id" 
                   style="background: #fafafa; border-radius: 8px; padding: 20px; border: 1px solid #f0f0f0; transition: all 0.3s;">
                <div style="display: flex; align-items: flex-start; gap: 16px;">
                  <a-avatar :size="44" :src="comment.userAvatar" style="flex-shrink: 0;">
                    {{ comment.username?.charAt(0)?.toUpperCase() }}
                  </a-avatar>
                  <div style="flex: 1; min-width: 0;">
                    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px;">
                      <div>
                        <div style="font-weight: 600; font-size: 15px; color: #333; margin-bottom: 4px;">{{ comment.username }}</div>
                        <div style="font-size: 13px; color: #999;">{{ comment.createTime }}</div>
                      </div>
                      <a-button 
                        v-if="comment.userId === currentUserId" 
                        type="text" 
                        danger 
                        size="small"
                        @click="handleDeleteComment(comment.id)"
                        style="margin-top: -4px;"
                      >
                        删除
                      </a-button>
                    </div>
                    <p style="margin: 0; color: #555; font-size: 15px; line-height: 1.8; word-break: break-word;">
                      {{ comment.content }}
                    </p>
                  </div>
                </div>
              </div>
              
              <div v-if="commentsPagination.total > commentsPagination.pageSize" style="text-align: center; margin-top: 20px;">
                <a-pagination
                  v-model:current="commentsPagination.current"
                  v-model:page-size="commentsPagination.pageSize"
                  :total="commentsPagination.total"
                  :show-size-changer="false"
                  :show-quick-jumper="true"
                  @change="loadComments"
                />
              </div>
            </div>
            
            <div v-else style="text-align: center; padding: 40px; color: #999;">
              <div style="font-size: 36px; margin-bottom: 12px;">💭</div>
              <p>暂无评论，快来发表第一条评论吧！</p>
            </div>
          </a-spin>
        </div>
        
        <!-- 无数据提示 -->
        <div v-if="!documentData.id && !loading" style="background: white; padding: 60px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); text-align: center;">
          <div style="font-size: 64px; margin-bottom: 20px;">📄</div>
          <p style="font-size: 16px; color: #999;">文档信息不存在或加载失败</p>
        </div>
        
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getLegalDocumentDetail, getFilePreviewUrl } from '@/api/document'
import { getCasePage } from '@/api/case'
import { getLawPage } from '@/api/document'
import { getCommentPage, addComment, deleteComment } from '@/api/comment'
import { checkFavorite, toggleFavorite } from '@/api/favorite'
import { getCurrentUserInfo } from '@/api/user'

const route = useRoute()
const router = useRouter()

// 数据状态
const documentData = ref({})
const relatedCases = ref([])
const relatedLaws = ref([])
const comments = ref([])
const loading = ref(false)
const casesLoading = ref(false)
const lawsLoading = ref(false)
const commentsLoading = ref(false)
const commentLoading = ref(false)
const favoriteLoading = ref(false)
const previewLoading = ref(false)

// 收藏状态
const isFavorited = ref(false)
const currentUserId = ref(null)

// 评论表单
const newComment = ref('')

// 分页状态
const casesPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
})

const lawsPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
})

const commentsPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
})

// 获取文档详情
const loadDocumentDetail = async (id) => {
  try {
    loading.value = true
    const response = await getLegalDocumentDetail(id)
    if (response.code === 200) {
      documentData.value = response.data || {}
      // 加载相关数据
      loadRelatedData()
    } else {
      message.error(response.msg || '获取文档详情失败')
    }
  } catch (error) {
    console.error('获取文档详情出错:', error)
    message.error('获取文档详情失败')
  } finally {
    loading.value = false
  }
}

// 加载相关数据
const loadRelatedData = () => {
  if (documentData.value.id) {
    loadRelatedCases()
    loadRelatedLaws()
    loadComments()
    checkFavoriteStatus()
  }
}

// 加载相关案件
const loadRelatedCases = async () => {
  try {
    casesLoading.value = true
    const response = await getCasePage({
      documentId: documentData.value.id,
      pageNum: casesPagination.value.current,
      pageSize: casesPagination.value.pageSize
    })
    if (response.code === 200) {
      relatedCases.value = response.data.records || []
      casesPagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取相关案件出错:', error)
  } finally {
    casesLoading.value = false
  }
}

// 加载相关法律条款
const loadRelatedLaws = async () => {
  try {
    lawsLoading.value = true
    const response = await getLawPage({
      documentId: documentData.value.id,
      pageNum: lawsPagination.value.current,
      pageSize: lawsPagination.value.pageSize
    })
    if (response.code === 200) {
      relatedLaws.value = response.data.records || []
      lawsPagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取相关法律条款出错:', error)
  } finally {
    lawsLoading.value = false
  }
}

// 获取文档类型颜色
const getDocTypeColor = (type) => {
  const colorMap = {
    0: 'blue',      // 法律
    1: 'green',     // 案例
    2: 'orange',    // 判决书
    3: 'purple'     // 文章
  }
  return colorMap[type] || 'default'
}

// 获取文档类型文本
const getDocTypeText = (type) => {
  const textMap = {
    0: '法律',
    1: '案例',
    2: '判决书',
    3: '文章'
  }
  return textMap[type] || '未知'
}

// 获取案件状态颜色
const getCaseStatusColor = (status) => {
  const colorMap = {
    0: 'processing',
    1: 'success',
    2: 'warning'
  }
  return colorMap[status] || 'default'
}

// 获取案件状态文本
const getCaseStatusText = (status) => {
  const statusMap = {
    0: '进行中',
    1: '已结案',
    2: '上诉'
  }
  return statusMap[status] || '未知'
}

// 查看案件详情
const viewCaseDetail = (item) => {
  router.push({ name: 'CaseDetail', params: { id: item.id } })
}

// 查看法律条款详情
const viewLawDetail = (item) => {
  router.push({ name: 'LawDetail', params: { id: item.id } })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 加载评论
const loadComments = async () => {
  try {
    commentsLoading.value = true
    const response = await getCommentPage({
      documentId: documentData.value.id,
      pageNum: commentsPagination.value.current,
      pageSize: commentsPagination.value.pageSize
    })
    if (response.code === 200) {
      comments.value = response.data.records || []
      commentsPagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取评论出错:', error)
  } finally {
    commentsLoading.value = false
  }
}

// 发表评论
const handleAddComment = async () => {
  if (!newComment.value.trim()) {
    message.warning('请输入评论内容')
    return
  }
  
  const token = localStorage.getItem('token')
  if (!token) {
    message.warning('请先登录')
    return
  }
  
  try {
    commentLoading.value = true
    const response = await addComment({
      documentId: documentData.value.id,
      content: newComment.value.trim()
    })
    if (response.code === 200) {
      message.success('评论发表成功')
      newComment.value = ''
      commentsPagination.value.current = 1
      loadComments()
    } else {
      message.error(response.msg || '评论发表失败')
    }
  } catch (error) {
    console.error('发表评论出错:', error)
    message.error('评论发表失败')
  } finally {
    commentLoading.value = false
  }
}

// 删除评论
const handleDeleteComment = async (commentId) => {
  try {
    const response = await deleteComment(commentId)
    if (response.code === 200) {
      message.success('评论删除成功')
      loadComments()
    } else {
      message.error(response.msg || '评论删除失败')
    }
  } catch (error) {
    console.error('删除评论出错:', error)
    message.error('评论删除失败')
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    const response = await checkFavorite({
      documentId: documentData.value.id
    })
    if (response.code === 200) {
      isFavorited.value = response.data || false
    }
  } catch (error) {
    console.error('检查收藏状态出错:', error)
  }
}

// 切换收藏状态
const handleToggleFavorite = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    message.warning('请先登录')
    return
  }
  
  try {
    favoriteLoading.value = true
    const response = await toggleFavorite({
      documentId: documentData.value.id
    })
    if (response.code === 200) {
      isFavorited.value = !isFavorited.value
      message.success(isFavorited.value ? '收藏成功' : '取消收藏成功')
    } else {
      message.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('切换收藏状态出错:', error)
    message.error('操作失败')
  } finally {
    favoriteLoading.value = false
  }
}

// 获取当前用户信息
const loadCurrentUser = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    const response = await getCurrentUserInfo()
    if (response.code === 200) {
      currentUserId.value = response.data.id
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
  }
}

// 从完整URL中提取objectName
const extractObjectName = (fullUrl) => {
  try {
    // fullUrl 格式: http://192.168.150.101:9000/legal-literature/documents/1/xxx.pdf
    // 需要提取: documents/1/xxx.pdf
    const url = new URL(fullUrl)
    const pathname = url.pathname
    // 去掉开头的 /legal-literature/ (bucket名称)
    const parts = pathname.split('/')
    // 找到bucket后面的路径
    const bucketIndex = parts.findIndex(part => part === 'legal-literature')
    if (bucketIndex !== -1 && bucketIndex < parts.length - 1) {
      return parts.slice(bucketIndex + 1).join('/')
    }
    return pathname.substring(1) // 去掉开头的 /
  } catch (error) {
    console.error('解析URL出错:', error)
    return fullUrl
  }
}

// 预览文件
const handlePreview = async () => {
  if (!documentData.value.fileUrl) {
    message.warning('该文档暂无文件')
    return
  }
  
  try {
    previewLoading.value = true
    // 从完整URL中提取objectName
    const objectName = extractObjectName(documentData.value.fileUrl)
    const response = await getFilePreviewUrl(objectName)
    
    if (response.code === 200) {
      const { previewUrl: url, fileType, canPreview } = response.data
      
      let finalUrl = ''
      // 根据文件类型选择预览方式
      if (fileType === 'pdf' || canPreview === 'true') {
        // PDF文件直接预览
        finalUrl = url
      } else if (fileType === 'doc' || fileType === 'docx') {
        // Word文件使用Office Online Viewer预览
        finalUrl = `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(url)}`
      } else {
        finalUrl = url
      }
      
      // 新开窗口预览
      window.open(finalUrl, '_blank')
      message.success('已打开预览窗口')
    } else {
      message.error(response.msg || '获取预览链接失败')
    }
  } catch (error) {
    console.error('预览文件出错:', error)
    message.error('预览失败')
  } finally {
    previewLoading.value = false
  }
}

// 下载文件
const handleDownload = () => {
  if (!documentData.value.fileUrl) {
    message.warning('该文档暂无文件')
    return
  }
  
  // 直接使用 fileUrl 字段下载（在当前窗口）
  window.location.href = documentData.value.fileUrl
  message.success('开始下载文件')
}

// 页面加载
onMounted(() => {
  const docId = route.params.id
  if (docId) {
    loadDocumentDetail(docId)
    loadCurrentUser()
  }
})
</script>

<style>
/* 文档详情页样式 */
</style>
